package datastructure.linkedlist;

/**
 *
 * @author Lei Zhang
 */
public class ReverseList {
  // recursive way without head pointer
  public static Node method2(Node p) {
    if (p == null) {
      return null;
    }
    if (p.next == null) {
      return p;
    }

    Node secondItem = p.next;
    p.next = null;
    Node newP = method2(secondItem);
    secondItem.next = p;

    return newP;
  }

  // iterative way with head pointer
  public static void method1(Node p) {
    Node previous = null;
    Node current = p.next;

    while (current.next != null) {

      Node next = current.next;
      current.next = previous;
      previous = current;
      current = next;
    }
    current.next = previous;
    p.next = current;
  }

  public static void main(String args[]) {

    Node n1 = new Node(1);
    Node n2 = new Node(2);
    Node n3 = new Node(3);
    Node n4 = new Node(4);

    n1.next = n2;
    n2.next = n3;
    n3.next = n4;

    Node p = new Node();
    p.next = n1;

    Node result = ReverseList.method2(n1);

    while (result != null) {
      System.out.println(result.value);
      result = result.next;
    }

  }
}
